package main

import (
	"encoding/json"
	"flag"
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
)

type Msg struct {
	RideFrom   int    `json:"rideFrom"`
	RideId     int    `json:"rideId"`
	RideStatus int    `json:"rideStatus"`
	TpoNo      string `json:"tpoNo"`
}

func main() {
	broker := "tcp://taxi-mqtt.jjtoyo.com:1883"
	mqttUsername := "njtoyo-taxi"
	mqttPassword := "njtoyo-taxi"

	rideId := flag.Int("ride", 114514, "receive rideId")
	taxiId := flag.Int("taxi", 114514, "receive rideId")
	rideStatus := flag.Int("state", 1, "state rideId")

	flag.Parse()
	fmt.Println("rideId:", *rideId)
	fmt.Println("taxiId:", *taxiId)
	// 创建MQTT客户端选项
	opts := mqtt.NewClientOptions().
		AddBroker(broker).
		SetClientID("client_from_239_test").
		SetCleanSession(true).
		SetKeepAlive(60).
		SetAutoReconnect(true).
		SetUsername(mqttUsername).
		SetPassword(mqttPassword)

	// 创建MQTT客户端实例
	client := mqtt.NewClient(opts)

	// 连接到broker aaa
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
	}
	fmt.Println("Connected to broker")

	//topic := "tpo/3600/monitor/"
	topic := fmt.Sprintf("tpo/%d/monitor/", *taxiId)

	var msg = Msg{
		RideFrom:   239,
		RideId:     *rideId,
		RideStatus: *rideStatus,
		TpoNo:      "tpoNo",
	}

	// 将结构体序列化为 JSON 字节数组
	payload, err := json.Marshal(msg)
	if err != nil {
		fmt.Println("Error marshaling message:", err)
		return
	}

	if token := client.Publish(topic, 0, false, payload); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
	}
	fmt.Println("Publish to broker")
}
